<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>在线聊天</title>
</head>
<body>
<div class="background">
    <my-header></my-header>
    <el-container class="container">

        <el-aside class="el-aside">

            <h3><i class="el-icon-edit"></i> 消息中心</h3>
            <el-menu
                    default-active="5"
                    class="el-menu-vertical-demo"
                    background-color="#eaf6fe"
                    text-color="#6b757b"
                    active-text-color="#2faee3"
            >
                <el-menu-item index="2">
                    <i class="el-icon-menu"></i>
                    <span slot="title">回复我的</span>
                </el-menu-item>
                <el-menu-item index="3" disabled>
                    <i class="el-icon-document"></i>
                    <span slot="title">@我的</span>
                </el-menu-item>
                <el-menu-item index="4">
                    <i class="el-icon-setting"></i>
                    <span slot="title">收到的赞</span>
                </el-menu-item>
                <el-menu-item index="5">
                    <i class="el-icon-setting"></i>
                    <span slot="title">我的消息</span>
                </el-menu-item>
            </el-menu>

        </el-aside>

        <el-main class="el-main">
            <el-row class="title">
                <div>我的消息</div>
            </el-row>

            <el-row class="message">
                <el-col :span="6" class="message-list">
                    <div><h3 style="text-align: center;height: 10px">近期消息</h3></div>

                    <el-divider></el-divider>
                    <!-- 消息列表 -->
                    <div :class="curSessionId == item.id ? 'message-item selected' : 'message-item'" v-for="item in sessionList_already" :key="item.id" @click="startSession(item.id)">
                        <el-avatar :size="40" fit="fill" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"></el-avatar>
                        <div class="message-sender">{{ item.listName }}</div>
                        <div class="message-unread">{{ item.unReadCount }}</div>
                        <i class="el-icon-close message-close" @click="delSession(item.id)"></i>
                    </div>
                </el-col>

                <h3 style="text-align: center;height: 14px">用户名字</h3>
                <!-- 聊天消息 -->
                <el-col :span="18" class="chat-window">
                    <div class="messageView">
                        <div v-for="(item, index) in list" :key="index" :class="item.fromUserId === curUserId ? 'msg_right' : 'msg_left'">
                            <div class="msg_right_up">
                                <el-avatar :size="40" fit="fill" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"></el-avatar>
                                {{item.fromUserName}}
                            </div>
                            <div :class="item.fromUserId === curUserId ? 'msg_right_down' : 'msg_left_down'">
                                {{item.content}}
                            </div>
                        </div>
                        <!--            <el-divider></el-divider>-->
                    </div>
                    <!-- 输入框 -->
                    <span class="emoji-picker" id="emoji-picker">😀</span>
                    <div class="input-box">
                        <el-input
                                class="input"
                                type="textarea"
                                :rows="5"
                                placeholder="请输入内容，回车发送！"
                                v-model="textarea"
                                @keyup.enter.native="sendMsg"
                        ></el-input>

                        <el-button @click="sendMsg" style="margin-left: 10px;">发送</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-main>
    </el-container>
</div>
</body>

<script>
    let v = new vue({
        data(){
            return{
                dialogVisible: false,     //登录,注册状态
                dialogTitle: '',          //
                loginName: '',            //登录者名字
                textarea: "",             //文本框输入信息
                list: [],                 //
                curUserId: "",            //会话目标id
                curUserName: "",          //会话目标名字
                curSessionId: '',         //会话id
                sessionList_already:[],   //已创建会话列表
                sessionList_not:[],       //为创建会话列表
            }
        },
        created() { // 页面创建生命周期函数

        },
        updated(){
            // 解决每次发消息到最后面
            const elmnt = document.getElementById("msg_end");
            elmnt.scrollTop = elmnt.scrollHeight;
        },
        destroyed: function () { // 离开页面生命周期函数
            this.websocketclose();
        },
        methods: {
            initWebSocket: function (userId, sessionId) {
                // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
                this.websock = new WebSocket("ws://127.0.0.1:8088/websocket/" + userId + "/" + sessionId);
                this.websock.onopen = this.websocketonopen;
                this.websock.onerror = this.websocketonerror;
                this.websock.onmessage = this.websocketonmessage;
                this.websock.onclose = this.websocketclose;
            },
            websocketonopen: function () {
                console.log("WebSocket连接成功");
            },
            websocketonerror: function (e) {
                console.log("WebSocket连接发生错误", e);
            },
            websocketonmessage: function (e) {
                let data = JSON.parse(e.data);
                if (data instanceof Array) {
                    // 列表数据
                    this.sessionList_already = data
                } else {
                    // 消息数据
                    this.list.push(data)
                }
            },
            websocketclose: function (e) {
                if (this.curUserId != null) {
                    if (this.curSessionId != null) {
                        this.initWebSocket(this.curUserId, this.curSessionId)
                    } else {
                        this.initWebSocket(this.curUserId, 99999999)
                    }
                }
                console.log("connection closed", e);
                console.log(e);
            },
            // 消息发送
            sendMsg() {
                if (this.curSessionId == '') {
                    return this.$message.error("请选择左边的对话框开始聊天!")
                }
                let data = {
                    "fromUserId": this.curUserId,
                    "fromUserName": this.curUserName,
                    "content": this.textarea
                }
                this.list.push(data)
                this.websock.send(this.textarea)
                this.textarea = ''
            },

            openDialog(openName) {
                this.dialogTitle = openName
                this.dialogVisible = true
            },
            // 登录or注册

            loginOrRegister() {
                let thus = this
                if (this.dialogTitle == "注册") {
                    axios.get('http://127.0.0.1:1997/register?name=' + this.loginName)
                        .then(function (response) {
                            if (response.data.code == -1) {
                                return thus.$message.error(response.data.errDesc);
                            }
                            thus.$message.success("注册成功");
                            thus.dialogVisible = false
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                } else if (this.dialogTitle == '登录') {
                    axios.get('http://127.0.0.1:1997/login?name=' + this.loginName)
                        .then(function (response) {
                            console.log(response.data);
                            if (response.data.code == -1) {
                                return thus.$message.error(response.data.errDesc);
                            }
                            thus.curUserId = response.data.data.id
                            thus.curUserName = response.data.data.name
                            thus.dialogVisible = false
                            thus.getSessionListNot()
                            thus.sessionListAlready()
                            thus.startSession(99999999)
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                }
            },

            // 获取可建立会话列表
            getSessionListNot() {
                let thus = this
                axios.get("/v1/sessionList/not?id=" + this.curUserId)
                    .then(function (response) {
                        if (response.data.code == -1) {
                            return thus.$message.error(response.data.errDesc);
                        }
                        thus.sessionList_not = response.data.data
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            // 获取已存在的会话列表
            sessionListAlready() {
                let thus = this
                axios.get("/v1/sessionList/already?id=" + this.curUserId)
                    .then(function (response) {
                        if (response.data.code == -1) {
                            return thus.$message.error(response.data.errDesc);
                        }
                        thus.sessionList_already = response.data.data
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            // 创建会话
            createSession(toUserId, toUserName) {
                let thus = this
                axios.get("/v1/sessionList/create?id=" + this.curUserId + "&toUserId=" + toUserId + "&toUserName=" + toUserName)
                    .then(function (response) {
                        if (response.data.code == -1) {
                            return thus.$message.error(response.data.errDesc);
                        }
                        thus.getSessionListNot()
                        thus.sessionListAlready()
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            // 开始会话
            startSession(sessionId) {
                console.log(this.websock);
                if (this.websock != undefined) {
                    this.websock.close()
                }
                this.curSessionId = sessionId
                this.initWebSocket(this.curUserId, sessionId)
                this.msgList(sessionId)
            },
            // 删除会话
            delSession(sessionId) {
                let thus = this
                axios.get("/v1/sessionList/delect?sessionId=" + sessionId)
                    .then(function (response) {
                        if (response.data.code == -1) {
                            return thus.$message.error(response.data.errDesc);
                        }
                        thus.getSessionListNot()
                        thus.sessionListAlready()
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            // 退出登录
            loginOut() {
                let thus = this
                axios.get('http://127.0.0.1:8088/loginOut?name=' + this.curUserName)
                    .then(function (response) {
                        if (response.data.code == -1) {
                            return thus.$message.error(response.data.errDesc);
                        }
                        thus.curUserId = ''
                        thus.curUserName = ''
                        return thus.$message.success("退出登录成功");
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            // 获取消息数据
            msgList(sessionId) {
                let thus = this
                axios.get("/v1/message/messageList?sessionId=" + sessionId)
                    .then(function (response) {
                        if (response.data.code == -1) {
                            return thus.$message.error(response.data.errDesc);
                        }
                        thus.list = response.data.data
                        // 从新获取列表
                        thus.sessionListAlready()
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            }
        }
    })
</script>
<style>
    .background {
        background-color: #81c3f3;
        background-repeat: no-repeat;
        background-size: cover;
    }
    .container{
        border: 1px solid #d9d9d9;
        margin-left: 10%;
        margin-right: 10%;
        margin-bottom: 0;
    }
    .el-aside {
        background-color:#eaf6fe;
        color: #333;
        padding: 20px;
        line-height: 30px;
        text-align: center;
    }
    .el-aside h3 {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 20px;
    }
    .el-aside ul {
        list-style-type: none;
        padding: 0;
    }
    .el-aside ul li {
        cursor: pointer;
        margin-bottom: 10px;
    }
    .el-main {
        background-color: #f7f7f7;
        color: #333;
        padding: 20px;
    }
    .title {
        background-color: #14e5bb;
        text-align: center;
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 20px;
        border-radius: 5px
    }
    .message{
        background-color: #fafafc;
        border-radius: 4px
    }
    .message-list {
        /*border-right: 1px solid #d9d9d9;*/
        overflow-y: auto;
        height: 400px;
    }
    .message-sender {
        text-align: center;
        flex-grow: 1;
    }
    .message-unread {
        background-color: #ff4d4f;
        color: #fff;
        border-radius: 50%;
        width: 20px;
        height: 20px;
        line-height: 20px;
        text-align: center;
    }
    .message-close {
        color: #999;
        cursor: pointer;
    }
    .messageView{
        height: 550px;
        overflow-y: auto;
        flex-grow: 1;
        border-bottom: #999999 solid 1px;
    }
    .input-box {
        display: flex;
        align-items: flex-end;
        margin-top: 20px;
        border-color: transparent;
        color: #00D4FF;
    }
    .input{
        flex-grow: 1;
        color: #00D4FF;
        background: transparent !important;
    }

    .message-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        padding: 5px;
        cursor: pointer;
        transition: background-color 0.3s;
    }
    .message-item:hover {
        background-color: #f5f5f5;
    }
    .selected {
        background-color: #f5f5f5;
    }

    .chat-window {
        display: flex;
        flex-direction: column;
        height: 650px;
        width: 650PX;
        background-color: white;
        border: 1px solid #ccc;
        margin: 20px auto;
        padding: 20px;
    }

    .emoji-picker {
        margin-left: 10px;
        cursor: pointer;
    }

    .chat-input {
        display: flex;
        align-items: center;
        margin-top: 10px;
        flex-grow: 1;
    }

    .msg_left{
        width: 500px;
        /* padding-left: 5px; */
        margin-top: 5px;
        /* border: 1px #1890ff solid; */
    }
    .msg_right{
        width: 500px;
        /* padding-right: 20px; */
        margin-top: 5px;
        /* border: 1px #1890ff solid; */
        text-align: right;
    }
    .msg_left_up{
        height: 25px;
        margin-top: 5px;
    }
    .msg_left_down{
        height: 25px;
        /* border: 1px #1890ff solid; */
        padding-left: 10px;
    }

    .msg_right_up{
        height: 25px;
    }
    .msg_right_down{
        height: 25px;
        /* border: 1px #1890ff solid; */
        padding-right: 10px;
    }
    .down{
        width: 680px;
        height: 200px;
        /* border: 1px red solid; */
    }
    .chat-input el-input {
        flex-grow: 1;
        margin-right: 10px;
    }
    .chat-input el-button {
        width: 80px;
    }
</style>


<!--import axios-->
<script src="https://cdn.bootcss.com/axios/0.18.0/axios.min.js"></script>

<!-- import Vue before Element -->
<script src="https://cdn.staticfile.org/vue/2.6.14/vue.min.js"></script>

<!-- import JavaScript -->
<script src="https://cdn.staticfile.org/element-ui/2.15.9/index.min.js"></script>
<!--引入自己的js文件-->
<script src="js/my-header.js"></script>
<script src="js/my-footer.js"></script>

</html>
